<?php

namespace App\Listeners;

use App\Events\ServiceOrderVerify;
use App\Models\Service;
use App\Models\ServiceSnapshot;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class ServiceOrder
{
    protected $model = null;

    /**
     * 响应service order事件
     * @param ServiceOrderVerify $event
     */
    public function handle(ServiceOrderVerify $event)
    {
        $this->model = $event->model;
        if ($this->model->id) {
            // 状态改变
            $this->status();;
        }else{
            // 新创建
            $this->creating();
        }
    }

    /**
     * 创建订单同步数据
     */
    protected function creating(){
        // 同步service信息
        $serv = Service::find($this->model->service_id);
        if ($serv) {
            $this->model->service_user_id = $serv->user_id;
            $this->model->price = $serv->price; // 成交价
            $this->model->status = \App\Models\ServiceOrder::$waitPay;  // 待支付
            $this->model->start_time = 0;
        }
    }

    /**
     * 状态改变改变数据
     */
    protected function status()
    {
        // 状态变动前创建快照
        if ( !$this->model->wasChanged('service_snapshot_id')) {
            // 用户信息
            $user = User::find( $this->model->user_id);
            // 服务信息
            $serv = Service::find($this->model->service_id);
            $shot = $snapshot =ServiceSnapshot::create([
                'user_nickname' => $user->nickname,
                'user_icon' => $user->icon,
                'user_phone'=> $user->phone,
                'user_province' => $user->province_id,
                'user_city' => $user->city_id,
                'user_district'=> $user->district_id,
                'service_category' => $serv->category_id ,
                'service_name' => $serv->name,
                'service_price' => $serv->price ,
                'service_time' => $serv->time,
                'service_remarks' => $serv->remarks,
                'service_media'=> '',
            ]);
            $this->model->service_snapshot_id = $shot->id;
        }

        // 订单确认。则更新订单开始时间
        if ($this->model->staus == 1) {
            $this->model->start_time = time();
        }
    }
}
